<template>
  <a-layout-header class="header" >
    <div  class="flex1">
      <button @click="handleExpand" v-if="!collapsed" class="ksd-absexpand"><MenuFoldOutlined style="font-size:18px;color:#666;"/></button>
      <button @click="handleExpand" v-else class="ksd-absexpand-r"><MenuUnfoldOutlined style="font-size:18px;color:#666;"/></button>
      <button @click="handleReload" class="ml20"><RedoOutlined style="font-size:18px;color:#666;"/></button>
    </div>
   <div class="flex align-items" >
     <a-dropdown>
       <a class="ant-dropdown-link flex align-items" >
         <img :src="userStore.avatar" style="height: 24px;width: 24px;border-radius: 50%;"/>
         <span class="ml10 mr10">{{userStore.username}}</span>
         <span>[{{currentRole?.name}}]</span>
         <DownOutlined />
       </a>
       <template #overlay>
         <a-menu>
           <a-menu-item v-for="(role) in userStore.roles" :key="role.id"  @click.prevent="handleChange(role)">
             <a href="javascript:;"><span v-if="role.active">当前角色是：</span>{{role.name}}</a>
           </a-menu-item>
         </a-menu>
       </template>
     </a-dropdown>

     <div class="ml15">
       <nuxt-link to="/login" v-if="!userStore.isLogin">去登录</nuxt-link>
       <button @click="handleLogout" v-else>退出</button>
     </div>
   </div>
  </a-layout-header>
</template>



<script setup>
const emits = defineEmits(["expand"])
const collapsed = ref(false)

const userStore = useStore.userState();
const currentRole = computed(()=>userStore.roles.find(c=>c.active))

const handleExpand = ()=>{
  collapsed.value = !collapsed.value
  emits("expand")
}

const handleReload = ()=>{
  window.location.reload()
}

const handleChange = async (role)=>{
  if ( currentRole.id == role.id ) return
  userStore.roles.filter(c=>c.active).map(c=>{ c.active=false })
  userStore.roles.find(c=>c.id==role.id).active = true;
  currentRole.value == role

  const resp = await useHandleChangeRoleApi(role.id)
  userStore.setMenuApis(resp.data)
  
}

const handleLogout = ()=>{
  Modal.confirm({
    title: '退出提示',
    content: '你确定要离开吗？',
    onOk() {
      useLogout()
    },
    onCancel() {},
  });
}

const onClick = (data)=>{
  if(data.key == 3){
    if(process.client) {
      Modal.confirm({
        content: '你确定要退出吗？',
        okText:"确定",
        cancelText: '取消',
        onOk() {
          useLogout()
        },
        onCancel() {

        },
      });

    }
  }
}

</script>
<style scoped>
.header {
  display: flex;
  position:sticky;
  top:0;
  justify-content: space-between;
  align-content: center;
  align-items: center;
  padding:0 20px;
  background:#fff;
  border:1px solid rgba(5, 5, 5, 0.06);
}

</style>